package com.lfx.concurrent.queue;

/**
 * @author 李逢喜
 * create 2021/7/22
 */
public class MyQueueMutil extends MyQueue {

    private String[] data=new String[10];

    private int size=0;

    private int getIndex=0;

    private int puIndex=0;




    /**
     * 插入数据
     * @param element
     */
    public  synchronized void  put(String element){

        if(size==data.length){//队列已满
            try {
                System.out.println("队列满了");
                //线程阻塞
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //没有获取到锁，进行递归获取锁
            put(element);
        }else {
            data[puIndex]=element;
            ++puIndex;
            if(puIndex==data.length)
                puIndex= 0;
            size++;
            notify();
        }

    }



    public synchronized String get(){
        if (size==0){//队列为空，阻塞
            try {
                System.out.println("队列里面没有消息了");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return get();
        }else {
            String result=data[getIndex];
            ++getIndex;

            if(getIndex==data.length) getIndex=0;
            --size;
            //唤醒随机阻塞等待
            notify();
            return  result;
        }
    }
}
